package com.earthchen.core.support.shiro.filter;


import com.alibaba.fastjson.JSON;
import com.earthchen.core.enums.ResultEnum;
import com.earthchen.core.support.shiro.token.PasswordToken;
import com.earthchen.core.util.WebUtil;
import com.earthchen.core.vo.ResultVO;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 基于 用户名密码 的认证过滤器
 *
 * @author Administrator
 */
public class PasswordFilter extends AccessControlFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(PasswordFilter.class);


    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {

        Subject subject = getSubject(request, response);
        // 如果其已经登录，再此发送登录请求
        return null != subject && subject.isAuthenticated();
        //  拒绝，统一交给 onAccessDenied 处理
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        //判断是否需要特殊处理的请求
        if (isSpecialRequest(request)) {
            return true;
        }
        ResultVO resultVO = ResultVO.error(ResultEnum.ERROR_REQUEST);
        WebUtil.responseWrite(JSON.toJSONString(resultVO), response);
        return false;
    }

    /**
     * 判断是否是特殊请求
     *
     * @param request
     * @return
     */
    private boolean isSpecialRequest(ServletRequest request) {
        String uri = ((HttpServletRequest) request).getRequestURI();
        return "/account/login".equals(uri) || "/account/register".equals(uri);
    }
}
